<?php
namespace app\shop\library\order\item;

use app\shop\library\order\Order;
use app\shop\library\coupon\MemberCoupon;

class freightCoupon extends goodsCoupon{

    public function count(Order &$order){

        if (!isset($this->post['freightCoupon']) ||  $this->post['freightCoupon']=='') return;

        $this->memberCouponId =  $this->post['freightCoupon'];  
        
            $goodsData = $order->list();
            $totalDiscount = 0;
             
            $couponUserData =  MemberCoupon::get($this->memberCouponId);
            
            if (!$couponUserData){
                throw new \Exception('优惠券不正确 02');
            }

            $coupon =   $couponUserData['coupon'];

            $couponGoodsList = $this->MatchGoodsList($goodsData,$coupon);

            $goodsPrice  = 0;

            foreach ($couponGoodsList as $goodsItem){
                $goodsPrice += $goodsItem['pay'];
                $this->usedGoods[] = $goodsItem['goods_id']; 
            }

            if ($goodsPrice < $coupon['condition_price']){
                throw new \Exception('优惠券不正确 03');
            }

            if ($goodsPrice <=0){
                throw new \Exception('优惠券不正确 04');
            }

            if ($order->detail('freight')['money'] < $coupon['price']){
                throw new \Exception('优惠券不正确 14');
            }

            $totalDiscount = $coupon['price'];
        
        $this->save_lab = true;
        $order->addDetail('coupon',$totalDiscount*-1);
    }

}